package com.editso.haier.storage;

import com.editso.haier.util.Utils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

public class UpFileItem implements Storage.FileItem {
    private final MultipartFile file;

    public UpFileItem(MultipartFile file) {
        this.file = file;
    }

    @Override
    public boolean isDirectory() {
        return false;
    }

    @Override
    public boolean isFile() {
        return true;
    }

    @Override
    public String getName() {
        return file.getOriginalFilename();
    }

    @Override
    public String getPath() {
        return null;
    }

    @Override
    public String getContentType() {
        return file.getContentType();
    }

    @Override
    public long getLength() {
        return file.getSize();
    }

    @Override
    public InputStream stream() throws IOException {
        return file.getInputStream();
    }

    public String geHexFileName() throws IOException {
        return Utils.joinSuffix(
                Utils.md5ToString(getBytes()),
                Utils.getSuffix(getName()));
    }

    public byte[] getBytes() throws IOException {
        return file.getBytes();
    }

    public static UpFileItem from(MultipartFile file){
        return file != null ? new UpFileItem(file) : null;
    }
}
